using System.Drawing;
using System.Windows.Forms;
using CloudShot.Editor.CanvasFigures;
using CloudShot.Entities;
using CloudShot.Interfaces;

namespace CloudShot.Editor.Tools
{
  /// <summary>
  ///   Line tool
  /// </summary>
  internal sealed class ArrowTool : ObjectCreationTool<CanvasArrow>
  {
    private const int MinimumArrowSize = 15;
    private readonly FigureSettings _figureSettings;

    public ArrowTool(IDrawingCanvas drawingCanvas, FigureSettings figureSettings, Section changeToolsSection, Section resetToolSection, Cursor cursor)
      : base(drawingCanvas, changeToolsSection, resetToolSection, cursor)
    {
      _figureSettings = figureSettings;
    }

    public override void OnMouseDown(MouseEventArgs e)
    {
      base.OnMouseDown(e);

      var line = new CanvasArrow(e.X, e.Y, e.X + 1, e.Y + 1)
      {
        BorderColor = _figureSettings.BorderColor,
        BorderWidth = _figureSettings.BorderWidth,
        LineType = _figureSettings.LineType,
        IsArrowAtStart = _figureSettings.IsArrowAtStart,
        IsArrowAtEnd = _figureSettings.IsArrowAtEnd
      };

      AddNewObject(Canvas, line);
    }

    public override void OnMouseMove(MouseEventArgs e)
    {
      base.OnMouseMove(e);

      if (e.Button == MouseButtons.Left)
      {
        var point = new Point(e.X, e.Y);

        using (new AutomaticCanvasRefresher(Canvas, CreatedObject.GetBoundingBox))
        {
          CreatedObject.MoveHandleTo(point, ArrowVertexType.End, Canvas.IsAnyModifierPressed(KeyModifiers.Shift));
        }
      }
    }

    public override void OnMouseUp(MouseEventArgs e)
    {
      base.OnMouseUp(e);

      var rect = CreatedObject.GetBoundingBox();
      if (rect.Width <= MinimumArrowSize && rect.Height <= MinimumArrowSize)
      {
        using (new AutomaticCanvasRefresher(Canvas, CreatedObject.GetBoundingBox))
        {
          Point location = e.Location;
          location.Offset(_figureSettings.Width, 0);
          CreatedObject.MoveHandleTo(location, 3);
        }
      }
    }
  }
}